﻿using Domain.Entitys.Base_Manage;
using Domain.IRepositorys.Base_Manage;
using Microsoft.EntityFrameworkCore;

namespace EFCore.Repositorys.Base_Manage
{
    public class RolesRepository : IRolesRepository
    {
        private readonly MyDbContext myDbContext;

        public RolesRepository(MyDbContext myDbContext)
        {
            this.myDbContext = myDbContext;
        }

        /// <summary>
        /// 根据用户ID查询对应角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Sys_Role> GetRolesAsync(int userId)
        {
            return await myDbContext.Sys_User_Role.Where(r => r.User_id == userId).Join(
                myDbContext.Sys_Role,
                ur => ur.Role_id,
                r => r.Role_id,
                (ur, r) => r).FirstOrDefaultAsync();
        }

        /// <summary>
        /// 查询所有可用角色
        /// </summary>
        /// <returns></returns>
        public async Task<List<Sys_Role>> GetRolesFillAsync()
        {
            return await myDbContext.Sys_Role.Where(r => r.Del_flag == '0').ToListAsync();
        }

        /// <summary>
        /// 添加用户角色信息
        /// </summary>
        /// <param name="sys_UserRoles"></param>
        /// <returns></returns>
        public async Task<int> UserRolesAddAsync(Sys_User_Role sys_UserRoles)
        {
            await myDbContext.Sys_User_Role.AddAsync(sys_UserRoles);
            return await myDbContext.SaveChangesAsync();
        }

        /// <summary>
        /// 根据用户ID删除用户角色信息
        /// </summary>
        /// <param name="sys_UserRoles"></param>
        /// <returns></returns>
        public async Task<int> UserRolesRemoveAsync(int userId)
        {
            Sys_User_Role sys_UserRoles = myDbContext.Sys_User_Role.FirstOrDefault(ur => ur.User_id == userId);
            myDbContext.Sys_User_Role.Remove(sys_UserRoles);
            return await myDbContext.SaveChangesAsync();
        }
    }
}
